﻿Imports System.ComponentModel
Imports System.Windows.Controls
Imports Microsoft.LightSwitch
Imports Microsoft.LightSwitch.Client
Imports Microsoft.LightSwitch.Presentation
Imports Microsoft.LightSwitch.Threading
Imports Microsoft.LightSwitch.Presentation.Extensions

Public Class DialogHelper
    Private _collection As IVisualCollection
    Private _dialogName As String
    Private _entityName As String
    Private _screen As IScreenObject
    Private _window As IContentItemProxy
    Private _entity As IEntityObject

    Public Sub New( _
    ByVal visualCollection As IVisualCollection _
    , ByVal dialogName As String _
    , Optional entityName As String = "" _
    )
        _collection = visualCollection
        _dialogName = dialogName
        _entityName = If(entityName <> "", entityName, _collection.Details.GetModel.ElementType.Name)
        _screen = _collection.Screen
    End Sub

    Public Sub Initialise()
        _window = _screen.FindControl(_dialogName)

        AddHandler _window.ControlAvailable, _
        Sub(s As Object, e As ControlAvailableEventArgs)
            Dim window = DirectCast(e.Control, ChildWindow)

            AddHandler window.Closed, _
             Sub(s1 As Object, e1 As EventArgs)
          DialogClosed(s1)
      End Sub
        End Sub
    End Sub

    Public Function CanAdd() As Boolean
        Return (_collection.CanAddNew = True)
    End Function

    Public Function CanView() As Boolean
        Return (_collection.SelectedItem IsNot Nothing)
    End Function

    Public Sub AddEntity()
        Dim result As IEntityObject = Nothing

        _window.DisplayName = String.Format("Add {0}", _entityName)
        _collection.AddNew()

        OpenModalWindow()
    End Sub

    Public Sub ViewEntity()
        _window.DisplayName = String.Format("View {0}", _entityName)

        OpenModalWindow()
    End Sub

    Private Sub OpenModalWindow()
        _entity = TryCast(_collection.SelectedItem, IEntityObject)
        _screen.OpenModalWindow(_dialogName)
    End Sub

    Public Sub DialogOk()
        If (_entity IsNot Nothing) _
        Then
            _screen.CloseModalWindow(_dialogName)
        End If
    End Sub

    Public Sub DialogCancel()
        If (_entity IsNot Nothing) _
        Then
            _screen.CloseModalWindow(_dialogName)
            DiscardChanges()

        End If
    End Sub

    Public Sub DialogClosed(sender As Object)
        Dim window = DirectCast(sender, ChildWindow)

        If (window.DialogResult.HasValue = False) _
        Then
            DiscardChanges()
        End If
    End Sub

    Private Sub DiscardChanges()
        If (_entity IsNot Nothing) _
        Then
            _entity.Details.DiscardChanges()
        End If
    End Sub
End Class